package programmercarl.动态规划.C16;

import java.util.Arrays;

class Solution1 {
    public int findTargetSumWays(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int sum = Arrays.stream(nums).sum();
        if (sum < Math.abs(target)) {
            return 0;
        }
        if ((sum + target) % 2 != 0) {
            return 0;
        }
        int bagSize = (sum+target) / 2;
        //0-i-1放满bagSize有多少种方法？
        int[][] dp = new int[nums.length][bagSize + 1];
        if (nums[0] <= bagSize) {
            dp[0][nums[0]] = 1;
        }
        int numsOfZeros =0;
        for (int i = 0; i < nums.length; i++) {//放满容量为0的背包
            if(nums[i]==0){
                numsOfZeros++;
            }
            dp[i][0] = (int) Math.pow(2,numsOfZeros);
        }
        for (int i = 1; i < nums.length; i++) {
            for (int j = 1; j <= bagSize; j++) {
                //若太大，可能放不下去
                if (nums[i] > j) {
                    dp[i][j] = dp[i - 1][j];
                } else {
                    //放i和不放i
                    dp[i][j] = dp[i - 1][j] + dp[i - 1][j - nums[i]];
                }
            }
        }
        return dp[nums.length - 1][bagSize];
    }

    public static void main(String[] args) {
        Solution1 solution1 = new Solution1();
        System.out.println(solution1.findTargetSumWays(new int[]{0,0,0,0,0,0,0,0,1}, 1));
    }
}